define(function(require, exports, module) {
    // 手机端 点透 问题
    require('{component}popup/popup.css');

    var popup = require('{component}popup/popup'),
        mId = 'play',
        domDudio, iosIsPlay, currTime,
        tpl = require("{view}play.tpl"),
        tplList = require("{view}songList.tpl"),
        listDate2, loadedPercentage,
        view = {

            template: _.template(tpl),
            templateList: _.template(tplList),

            render: function() {
                var tthis = this,
                    parameter = share.getParameter(),
                    songid = parameter.songid;

                if ($("#" + mId).attr('songid') == songid) {
                    share.showPage(mId)
                } else {
                    if ($("#" + mId).length < 1) {
                        $("body").append(this.template());
                        this.bindEvt();
                        share.showPage(mId);
                    }
                    this.switchSong(songid);
                    // $("#"+mId).find('.play_list ul').scrollTop(0);
                }

                this.renderPlayList(songid);
            },

            renderPlayList: function(songid) {

                var tthis = this,
                    dom = $("#" + mId),
                    songid = songid || dom.attr('songid'),
                    listDate = util.getLocalStorage('play_list'),
                    bool = _.isEqual(listDate, listDate2);

                if (dom.find('.play_list li').length < 0) bool = false;
                if (bool) return;

                listDate2 = util.getLocalStorage('play_list');

                dom.find('.play_list_box').html(tthis.templateList({ thisSongid: songid, data: listDate2 }));
                this.bindEvtList();
                this.setUlScroll();
            },

            setUlScroll: function() {
                var dom = $('#' + mId).find('.play_list'),
                    liHeight = dom.find('li').height(),
                    domUl = dom.find('ul'),
                    size = Math.floor(domUl.height() / liHeight),
                    topVal = liHeight * (dom.find('li.playing').index() - (size / 2));

                domUl.scrollTop(topVal);
            },

            reBindEvt: function() {
                var tthis = this,
                    dom = $("#" + mId),
                    jqaudio = dom.find(domDudio);
                dom.find('#cover_play,#bottom_play').off('click');
                setTimeout(function() { //移动端点透问题
                    dom.find('#cover_play,#bottom_play').on('tap', function() {
                        if (jqaudio.attr('autoplayBool') == 'true') {
                            domDudio.pause();
                        } else {
                            domDudio.play();
                        }
                        tthis.setPlaySwitch();
                    })
                }, 300)
            },

            setPlaySwitch: function() {

                var dom = $("#" + mId),
                    jqdomAudio = dom.find('audio');
                if (jqdomAudio.attr('autoplayBool') == 'true') {
                    dom.find('.play').removeClass('selected')
                    dom.find('.center_play').show().animate({ 'opacity': '1' }, 500);
                    dom.find('.cover img').removeClass('animate');
                    jqdomAudio.attr('autoplayBool', false)
                    window.controller.play.play = false;
                } else {
                    dom.find('.center_play').animate({ 'opacity': '0' }, 500, function() {
                        $(this).hide();
                    });
                    dom.find('.cover img').addClass('animate');
                    dom.find('.play').addClass('selected');
                    jqdomAudio.attr('autoplayBool', true)
                    window.controller.play.play = true;
                }
            },
            bindEvt: function() {
                var tthis = this,
                    dom = $("#" + mId),
                    domfooter = dom.find('.footer');
                // IOS兼容问题
                var ydom = document.getElementById('play');
                domDudio = ydom.getElementsByTagName('audio')[0];
                var jqaudio = dom.find(domDudio);

                domDudio.volume = '0.5';
                dom.find('#cover_play,#bottom_play').on('click', function() {
                    if (jqaudio.attr('autoplayBool')) {
                        domDudio.pause();
                    } else {
                        domDudio.play();
                        iosIsPlay = true;
                    }
                    tthis.setPlaySwitch();
                    tthis.reBindEvt();
                })

                dom.find('.ico_more').on('tap', function() {
                    var songid = dom.attr('songid'),
                        tinguid = dom.attr('tinguid');
                    popup.show({ type: 'more', tinguid: tinguid, songid: songid, li: ['all'] });
                });


                dom.find('.voice_range').on('change', function() {
                    var val = $(this).val() / 100;
                    domDudio.volume = val;
                });

                dom.find('.bar').on('touchstart', function(event) {

                    domDudio.play();
                    iosIsPlay = true;

                    tthis.setPlay();

                    var e = event.changedTouches[0],
                        x = e.clientX - $(this).offset().left,
                        val = (x / $(this).width()) * domDudio.duration;

                    domDudio.currentTime = val;
                    tthis.progressbar(); //bar 监控
                });


                domfooter.find('.list').on('tap', function(event) {
                    var domList = dom.find('.play_list_box'),
                        songid = dom.attr('songid');
                    share.popup(domList);

                    setTimeout(function() {
                            tthis.setUlScroll();
                        }, 500)
                        // popup.show({type:'songList',songid:songid,dom:domList});
                });

                domfooter.find('.shadow').on('tap', function(event) {
                    domfooter.find('.shadow').hide();
                    domfooter.find('.play_list').removeClass('show');
                });


                dom.find('.play_list span.right').on('tap', function() {
                    dom.find('.play_list li').remove();
                    dom.find('.play_list .list_head b').text(0)
                });

                dom.find('.back').on('tap', function() {
                    if (!share.go(-1)) {
                        window.location.href = '#found';
                    }
                });

                dom.find('.shareweb').on('tap', function() {
                    popup.show({ type: 'shareweb' });
                });

                dom.find('.loops').on('tap', function() {
                    var index = $(this).attr('index');

                    dom.find('.loops').attr('class', 'loops');
                    index++;
                    index >= 3 && (index = 0);
                    index == 0 && $(this).addClass('each');
                    index == 1 && $(this).addClass('one');
                    index == 2 && $(this).addClass('random');

                    $(this).attr('index', index);
                });

                dom.find('.play_box .before').on('tap', function() {
                    tthis.play(-1);
                });

                dom.find('.play_box .after').on('tap', function() {
                    tthis.play(+1);
                });

            },

            bindEvtList: function() {
                // list
                var domList = $('#' + mId).find('.play_list_box');

                domList.find('li').on('tap', function() {

                    var parameter = share.getParameter(),
                        songid = parameter.songid;

                    domList.find('li').removeClass('playing');
                    $(this).addClass('playing');
                    window.location.href = '#play?songid=' + $(this).attr('songid');
                })

                domList.find('li .ico_delete').on('tap', function(e) {
                    e.stopPropagation();
                    if ($(this).parents('li').hasClass('playing')) {
                        alert('这首歌正在播放哦！');
                        return;
                    }
                    $(this).parents('li').remove();
                });

                domList.find('.list_head span').on('tap', function() {
                    domList.find('.play_list ul').empty();
                    domList.find('.play_list strong').empty();
                })
            },

            play: function(val) {
                var index, songid,
                    dom = $("#" + mId),
                    curId = dom.attr('songid'),
                    listDate = util.getLocalStorage('play_list'),
                    songList = listDate.song_list || listDate.song || listDate.list || listDate.songlist;

                if ((!listDate) || songList.length <= 0) songid = curId;
                else {
                    $.each(songList, function(i) {
                        if (curId == (songList[i].song_id || songList[i].songid)) {
                            index = i;
                            return false;
                        }
                    });

                    val == -1 && index--;
                    val == +1 && index++;
                    index < 0 && (index = songList.length - 1);
                    index >= songList.length && (index = 0);
                    songid = songList[index].song_id || songList[index].songid;
                }
                this.setPlayListClass(index)
                this.switchSong(songid);
            },

            setPlayListClass: function(index) {
                var dom = $('#' + mId).find('.play_list');
                dom.find('li').removeClass('playing');
                dom.find('li').eq(index).addClass('playing');
            },

            setPlay: function() {
                var dom = $("#" + mId),
                    jqdomAudio = dom.find('audio');
                dom.find('.center_play').animate({ 'opacity': '0' }, 500, function() {
                    $(this).hide();
                });
                dom.find('.cover img').addClass('animate');
                dom.find('.play').addClass('selected');
                jqdomAudio.prop('autoplay', true)
                window.controller.play.play = true;
            },
            progressbar: function() {
                // setInterval setTimeout
                if ($('#' + mId).css('display') == 'none') return;
                if (!domDudio || !domDudio.duration) return;
                var tthis = this,
                    dom = $('#' + mId).find('.when'),
                    pointLeft,
                    m = domDudio.currentTime,
                    tm = domDudio.duration,
                    totalTime = share.fromTimes(tm),
                    playRate = m / tm;
                loadedPercentage = domDudio.buffered.end(0) / domDudio.duration;
                currTime = share.fromTimes(m);

                dom.find('.cur_time').text(currTime);
                dom.find('.total_time').text(totalTime);

                dom.find('.bg2').css({ 'width': (loadedPercentage * 100) + '%' });
                dom.find('.bg3').css({ 'width': (playRate * 100) + '%' });

                pointLeft = dom.find('.bar').width() * playRate;
                // dom.find('.point').css({'left':playRate*100 +'%'});
                dom.find('.point').css({ 'left': pointLeft - (dom.find('.point').width() / 2) + 'px' });

                if (m + 1 > tm * loadedPercentage) {
                    dom.find('.point').addClass('point_loading');
                } else {
                    dom.find('.point').removeClass('point_loading');
                }
                m >= tm && tthis.play(+1);

            },
            songMatch: function(cly) {

                var dom = $('#' + mId),
                    tthis = this,
                    newArr = [],
                    html = '';

                $.each(cly, function(i) {
                    if (cly[i].time == currTime) {
                        newArr.push(cly[i]);
                    }
                });

                if (newArr.length > 0) {
                    $.each(newArr, function(i) {
                        if (newArr[i].text) {
                            html += '<li>' + newArr[i].text + '</li>';
                        }
                    });
                    dom.find('.cly').find('ul').html(html);
                }
            },
            replaceSeconds: function(val) {
                if (val) {
                    var clyTime,
                        rep = val.replace(/\[(.*)\]/g, '$1'),
                        time = rep.split(/:/),
                        points = time[0],
                        s = Math.floor(time[1]) + '';

                    if (s == 'NaN') s = 0;
                    else s.length <= 1 && (s = '0' + s);

                    clyTime = points + ':' + s;
                    return clyTime;
                }
            },
            ajaxCly: function(id) {
                var dom = $('#' + mId),
                    tthis = this;
                $.ajax(share.ajax({
                    url: apiUrl,
                    data: { method: 'baidu.ting.song.lry', songid: id },
                    success: function(data) {

                        if (data.lrcContent) {
                            var clyArr = tthis.eachCly(data.lrcContent);
                            tthis.timeCly =
                                setInterval(function() {
                                    tthis.songMatch(clyArr);
                                }, 900);
                        } else {
                            dom.find('.cly ul').html('有没找到歌词...');
                        }
                    }
                }))
            },
            eachCly: function(val) {
                var dom = $('#' + mId),
                    tthis = this,
                    obj = {},
                    newArr = [],
                    arr = val.split('['),
                    html = '';
                $.each(arr, function(i) {
                    var t = arr[i];
                    arr[i] = '[' + t;
                })
                obj.arr = arr;
                $.each(obj.arr, function(i) {
                    var tObj = {};
                    tObj.time = obj.arr[i].match(/\[.*\]/) || ['[00:00]'];
                    tObj.time = tthis.replaceSeconds(tObj.time[0]);
                    tObj.text = obj.arr[i].replace(/\[.*\](.*)/, '$1');
                    if (tObj.text == '[') {
                        tObj.text = '';
                    }
                    newArr.push(tObj);
                })
                return newArr;
            },
            timeCly: null,
            timeBar: null,
            initText: function() {
                clearInterval(this.timeBar);
                clearInterval(this.timeCly);
                var dom = $('#' + mId),
                    tthis = this,
                    domBar = dom.find('.bar'),
                    domBarPointW = domBar.find('.point').width(),
                    imgUrl = 'resource/images/default_avatar1.png';

                dom.find('.cly ul').html('歌词加载中...');
                dom.find('.cover .imglazyload').attr({ 'src': imgUrl });

                dom.find('.cur_time').text('00:00');

                domBar.find('.bg2').css({ 'width': '0px' });
                domBar.find('.bg3').css({ 'width': '0px' });
                domBar.find('.point').attr({ 'class': 'point point_loading' }).css('left', -domBarPointW / 2 + 'px');

            },
            switchSong: function(id) {
                var dom = $('#' + mId),
                    tthis = this;
                this.initText();
                share.loading();
                console.log(apiUrl)
                $.ajax(share.ajax({
                    url: apiUrl,
                    data: { method: 'baidu.ting.song.play', songid: id },
                    success: function(data) {
                        // console.log(data)
                        if (data.error_code != 22000) {
                            alert('没有数据');
                            if (!share.go(-1)) {
                                window.location.href = '#found';
                            }
                            return;
                        }

                        var title = data.songinfo.title,
                            author = data.songinfo.author,
                            src = share.apiReplace(data.bitrate.file_link, apiUrlPlay),
                            imgSrc = data.songinfo.pic_big;

                        dom.find('audio').attr({ 'src': src }); //这个一定要在前面
                        iosIsPlay && domDudio.play();

                        dom.find('.head p').eq(0).text(title)
                        dom.find('.head p').eq(1).text(author);
                        dom.find('.cover .imglazyload').attr({ 'src': imgSrc });
                        dom.find('.mask').css({ 'backgroundImage': 'url(' + imgSrc + ')' });
                        dom.attr({ 'songid': id, 'tinguid': data.songinfo.ting_uid });

                        setTimeout(function() {
                            share.loading('hide');
                        }, 600);

                        share.showPage(mId);
                        tthis.ajaxCly(id);

                        tthis.timeBar =
                            setInterval(function() {
                                tthis.progressbar(); //bar 监控
                            }, 1000);

                        window.location.href = '#play?songid=' + id;
                    }
                }))
            },

        };

    view.ajaxBool = true;
    view.userNav = false;
    module.exports = view;
});
